# -*- coding: utf-8 -*-

from odoo import models, fields, api


class ApiConfig(models.Model):
    """API配置模型"""
    _name = 'device.api.config'
    _description = 'API配置'
    
    name = fields.Char('配置名称', required=True)
    key = fields.Char('配置键', required=True)
    value = fields.Text('配置值', required=True)
    description = fields.Text('配置描述')
    active = fields.Boolean('启用', default=True)
    
    _sql_constraints = [
        ('key_unique', 'unique(key)', '配置键必须唯一！')
    ]
    
    @api.model
    def get_config_value(self, key, default=None):
        """获取配置值"""
        config = self.search([('key', '=', key), ('active', '=', True)], limit=1)
        return config.value if config and config.exists() else default
    
    @api.model
    def set_config_value(self, key, value, name=None, description=None):
        """设置配置值"""
        config = self.search([('key', '=', key)], limit=1)
        if config:
            config.write({'value': value, 'active': True})
        else:
            self.create({
                'name': name or key,
                'key': key,
                'value': value,
                'description': description,
                'active': True
            })
    
    @api.model
    def get_jwt_secret(self):
        """获取JWT密钥"""
        secret = self.get_config_value('jwt_secret', 'abcdefghijklmnopqrstuvwxyz')
        # 如果没有配置记录，创建默认配置
        if secret == 'abcdefghijklmnopqrstuvwxyz':
            existing_config = self.search([('key', '=', 'jwt_secret')], limit=1)
            if not existing_config:
                self.create({
                    'name': 'JWT密钥',
                    'key': 'jwt_secret',
                    'value': 'abcdefghijklmnopqrstuvwxyz',
                    'description': 'JWT令牌加密密钥',
                    'active': True
                })
        return secret
    
    @api.model
    def get_jwt_expire_hours(self):
        """获取JWT过期时间（小时）"""
        return int(self.get_config_value('jwt_expire_hours', '24'))
    
    @api.model
    def is_cors_enabled(self):
        """是否启用CORS"""
        return self.get_config_value('cors_enabled', 'true').lower() == 'true'
    
    @api.model
    def get_cors_origins(self):
        """获取允许的CORS来源"""
        return self.get_config_value('cors_origins', '*')


class ResConfigSettings(models.TransientModel):
    """系统配置"""
    _inherit = 'res.config.settings'
    
    jwt_secret = fields.Char(
        '(JWT密钥', 
        config_parameter='device.jwt_secret',
        default='abcdefghijklmnopqrstuvwxyz'
    )
    jwt_expire_hours = fields.Integer(
        'JWT过期时间(小时)',
        config_parameter='device.jwt_expire_hours',
        default=24
    )
    cors_enabled = fields.Boolean(
        '启用CORS',
        config_parameter='device.cors_enabled',
        default=True
    )
    cors_origins = fields.Char(
        'CORS允许来源',
        config_parameter='device.cors_origins',
        default='*'
    )
